<!--
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-12-18 15:55:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-11-07 10:04:10
 * @FilePath: MultiLineChart.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <!-- 柱状图组合 -->
    <div class="MultiLineChartBox" :style="'height:' + Height + 'px;'">
        <!-- tab切换 -->
        <div class="tabBox">
            <el-radio-group size="small" v-model="activeName" @change="selectActive">
                <el-radio-button label="1">日均值</el-radio-button>
                <el-radio-button label="2">近30天</el-radio-button>
            </el-radio-group>
            <div class="averageBox">均值：{{ averageNum }}{{ Number(activeName) == 1 ? '分钟' : '小时' }}</div>
        </div>
        <!-- 图形 -->
        <div id="LineChart"></div>
    </div>
</template>
<script>
export default {
    name: 'MultiLineChart',
    props: {
        Height: {
            type: Number,
            default: 0,
        },
    },
    data() {
        return {
            activeName: '1',
            LineChart: null,
            dayTimeDate: {
                chartList: [],
                typeList: [],
                timeDate: [],
            },
            averageNum: 0
        }
    },
    mounted() {
        this.getInfo(Number(this.activeName))
        window.addEventListener('resize', () => {
            setTimeout(async () => {
                await this.lineChart.resize()
            }, 110)
        })
    },
    methods: {
        // 把数组yysName相同的数组组合在一起
        groupByName(type, items) {
            this.dayTimeDate.timeDate = []
            this.dayTimeDate.chartList = []
            this.dayTimeDate.typeList = []
            items.forEach(item => {
                if (!this.dayTimeDate.typeList.includes(item.yysName)) {
                    this.dayTimeDate.typeList.push(item.yysName)
                    this.dayTimeDate.chartList.push({
                        name: item.yysName,
                        type: 'line',
                        smooth: true,
                        showSymbol: false,
                        data: [],
                    })
                }
                if (Number(type) === 1) {
                    // 当天的
                    if (!this.dayTimeDate.timeDate.includes(`${item.callHour.slice(-2)}:00`)) {
                        this.dayTimeDate.timeDate.push(`${item.callHour.slice(-2)}:00`)
                    }
                } else {
                    if (!this.dayTimeDate.timeDate.includes(`${item.callDay.slice(5)}`)) {
                        this.dayTimeDate.timeDate.push(`${item.callDay.slice(5)}`)
                    }
                }
            })
        },
        // 拿到了数据 就去比对，把相同的数据放进一个数组里面 并且排序
        getConmeList(type, list) {
            list.forEach(item => {
                this.dayTimeDate.typeList.forEach((items, indexs) => {
                    if (item.yysName === items) {
                        // 如果名字相等
                        if (type === 1) {
                            this.dayTimeDate.chartList[indexs].data.push((Number(item.callSecond) / 60).toFixed(2))
                        } else {
                            this.dayTimeDate.chartList[indexs].data.push((Number(item.callSecond) / 3600).toFixed(2))
                        }

                    }
                })
            })
        },
        // 获取数据
        async getInfo(type) {
            const { data: res } = Number(type) === 1 ? await this.$http.get('/TalkScreen/Api/HlPhone/yysCallTime24Hour') : await this.$http.get('/TalkScreen/Api/HlPhone/yysCallTimeDays')
            // let arr = this.sortedList(res)
            await this.groupByName(type, res)
            await this.getConmeList(type, res)
            await this.getChart()
        },
        selectActive(val) {
            this.getInfo(Number(val))
        },
        // 求数据的平均值
        average(arr) {
            const sum = arr.reduce((a, b) => Number(a) + Number(b), 0);
            const avg = sum / arr.length;
            return avg.toFixed(2); // 保留两位小数
        },
        getChart() {
            var that = this
            that.lineChart = that.$echarts.init(document.getElementById('LineChart'))
            let arrList = []
            that.dayTimeDate.chartList.forEach(item => {
                item.data.forEach(items => {
                    arrList.push(items)
                })
            })
            this.averageNum = that.average(arrList)
            that.dayTimeDate.chartList.forEach((item, index) => {
                if (index === 0) {
                    item.markLine = {
                        data: [
                            {
                                name: '平均值',
                                type: 'average',
                                yAxis: that.average(arrList),
                                lineStyle: {
                                    color: '#4BEEFF',    // 线条颜色
                                    width: 1,       // 线条宽度
                                    type: 'dashed'    // 线条类型，默认为实线，可选：'solid', 'dashed', 'dotted'
                                },
                                label: {
                                    // formatter: `均值：${that.average(arrList)}${Number(that.activeName) === 1 ? '分钟' : '小时'}`,
                                    fontSize: '0px',
                                    // backgroundColor: 'rgba(44, 95, 196, 1)',
                                    // color: '#ffffff',
                                    // position: 'insideEndTop',
                                    // padding: [0, 10],
                                    // distance: [60, 5], // 设置标签文字的样式
                                    // // width: 72,
                                    // height: 24,
                                    // lineHeight: 22,
                                    // align: 'center',
                                    // borderRadius: 4,
                                }
                            }
                        ],

                    }
                }
            })
            // 获取坐标轴刻度最大值
            let maxVal = Number(Math.max(...arrList)) + 1;
            // 获取坐标轴刻度最小值
            let minVal = Number(Math.min(...arrList)) + 1;
            // 计算坐标轴分割间隔
            let interval = Math.floor((maxVal - minVal) / 5);
            let color = ['#1FA4F8', '#FFE401', '#F95B00', '#18C78B', '#AE1FB8', '#F79F83']
            var option = {
                color: color,
                title: {
                    text: `单位/${Number(that.activeName) === 1 ? '分钟' : '小时'}`,
                    top: that.$util.nowSizeWidth(100),
                    left: -5,
                    textStyle: {
                        color: '#FFFFFF',
                        fontSize: 12,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: "#fff",
                    extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
                    formatter: function (params) {
                        return (
                            `<span style='font-size: 12px;
                                font-family: Source Han Sans CN, Source Han Sans CN;
                                font-weight: bold;
                                color: #0A1F48;margin-left:-2px;margin-bottom:4px;display:inline-block;'>时间：${params[0].name}</span>` +
                            `<br>` +
                            params
                                .map((item) => {
                                    let str = `<span style="display:inline-block;vertical-align: middle;width:8px;height:8px;margin: 0 5px 0 0px;background-color:${item.color};"></span>`
                                    let seriesNameStr = `<span style="display:inline-block;font-size:12px;vertical-align: middle;">${item.seriesName}</span>`
                                    let value = item.value
                                    let valueStr = `<span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;">${value}${Number(that.activeName) === 1 ? '分钟' : '小时'}</span>`
                                    return `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
									<span>${str}${seriesNameStr}</span>
									<span>${valueStr}</span>
								</span>`
                                })
                                .join(``)
                        )
                    },
                },
                legend: {
                    orient: 'horizontal',
                    icon: 'rect',
                    top: that.$util.nowSizeWidth(52),
                    left: 0,
                    itemWidth: 9,
                    itemHeight: 9,
                    itemGap: 10,
                    textStyle: {
                        color: '#fff',
                        rich: {
                            a: {
                                verticalAlign: 'middle',
                            },
                        },
                        padding: [2, 0, 0, 0],
                    },
                    data: that.dayTimeDate.typeList
                },
                grid: {
                    left: 0,
                    right: 1,
                    bottom: 10,
                    top: that.$util.nowSizeWidth(130),
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#0D3B77',//左边线的颜色
                            width: '1'//坐标线的宽度
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#ffffff',//坐标值得具体的颜色
                            fontFamily: 'Arial',
                            fontSize: 12,
                            fontStyle: 'normal'
                        },
                        interval: 2,
                        formatter: function (value, index) {
                            if (index === 0) {
                                return '         ' + value;
                            }
                            if (index === that.dayTimeDate.timeDate.length - 1) {
                                return value + '         ';
                            }
                            return value;
                        }
                    },
                    interval: 0,
                    axisTick: false,
                    splitLine: {  //坐标轴在grid区域中的分隔线（网格中的横线）
                        show: true,
                        lineStyle: {
                            color: ['#0D3B77'],
                            width: 1,
                            type: 'dashed',
                        }
                    },
                    data: that.dayTimeDate.timeDate,
                    boundaryGap: false // 不留白，从原点开始
                },
                yAxis: {
                    type: 'value',
                    // min: minVal, // 坐标轴刻度最小值。
                    // max: maxVal, // 坐标轴刻度最大值。
                    // interval: interval, // 强制设置坐标轴分割间隔。
                    minInterval: 1,
                    scale: true,
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#2E3950',//左边线的颜色
                            width: '1',//坐标线的宽度
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#e6e6e6',//坐标值得具体的颜色
                        }
                    },
                    axisTick: false,
                    splitLine: {  //坐标轴在grid区域中的分隔线（网格中的横线）
                        show: false,
                        lineStyle: {
                            color: ['#0D3B77'],
                            width: 1,
                            type: 'dashed',
                        }
                    }
                },
                series: that.dayTimeDate.chartList
            }
            that.lineChart.setOption(option, true)
        },
    },
}
</script>
<style lang="less" scoped>
.MultiLineChartBox {
    width: 100%;
    position: relative;
    padding-bottom: 5px;

    .tabBox {
        width: 100%;
        position: absolute;
        top: 20px;
        left: 0px;
        z-index: 999;
    }

    .averageBox {
        position: absolute;
        top: 12%;
        right: 0px;
        font-size: 12px;
        color: #4BEEFF;
    }
    #LineChart {
        width: 100%;
        height: 100%;
    }
}
</style>